<?php
/**
 * IndexController.php for in /application/controllers/Default
 *
 * @brief root controller
 *
 * @category   BaseZF
 * @package    BaseZF
 * @copyright  Copyright (c) 2004-2007 Harold Thetiot
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

class ExampleController extends BaseZF_Framework_Controller_Action
{
	/**
	 * Index of Example action
	 */
	public function indexAction()
	{
        $this->view->title = 'Example Index';
	}


    public function phpInfoAction()
    {
        phpinfo();
        exit();
    }

    /**
     * Css stuff
     */
    public function cssLayoutAction()
	{
        $this->view->addStyle('/styles/layout.css');
    }

    public function toolTipsAction()
	{
        $this->view->addStyle('/styles/tooltips.css');
    }

    public function cssStartRatingAction()
	{
        $this->view->addStyle('/styles/starrating.css');
    }

    /**
     * Prototype and script.aculo.us
     */
    public function ajaxRequestAction()
    {
        $field = $this->_getParamFromAll('field');

        $this->view->params = array(
            'response_nocache' => null,
            'response_cache' => null
        );

        // detect is is ajax request
        if ($this->view->isAjax()) {

            // forward to ajax interpreter
            $this->_forward('ajaxrequestcallback');

        // else if not ajax but link
        } else if (!is_null($field)) {
            $this->view->params[$this->_getParamFromAll('field')] = time();
        }
    }

    public function ajaxRequestCallbackAction()
    {
        // set js code to exec
        $this->view->setJsCode('$(\'' . $this->_getParamFromAll('field') . '\').value = "' . time() . '"');
    }

    public function ajaxAutocompleterAction()
    {
        if ($this->view->isAjax()) {
            // forward to ajax interpreter
            $this->_forward('ajaxautocompletercallback');
        } else {
            // add js libs
            $this->view->addJavascript('/js/scriptaculous/scriptaculous.js');
        }
    }

    public function ajaxAutocompleterCallBackAction()
    {
         $this->view->autocompleter_value = $this->_getParamFromAll('autocompleter_value');
    }

    public function sortablelistAction()
    {
        $this->view->addJavascript('/js/scriptaculous/scriptaculous.js');
    }

    public function lightBoxAction()
	{
    }

    /**
     * Begin of BaseZF & Zend Example
     */
    public function errorhandlerAction()
	{
        throw new Exception('error Handler test');
    }

    public function translateAction()
	{
        // see view
    }

    public function cookiesAction()
	{
    }

    public function sessionAction()
	{
        // set params
        $params_array = array(
            'session_key',
            'value',
            'submit',
        );

        // get param from input
        $params = $this->_getParamFromFields($params_array);
        $paramsErrors = array();

        if (!is_null($params['submit'])) {

            // set filters
            $filters = array(
                '*'         => 'StringTrim',  // * to apply filter on all vars
            );

            // set validators
            $validators = array(
                'session_key'   => array('Alpha', 'allowEmpty' => false),
                'value'         => array('allowEmpty' => false),
            );

            // add filters and validator on $params
            $form = new Zend_Filter_Input($filters, $validators, $params);

            if ($form->hasInvalid()) {
                $paramsErrors = $form->getInvalid();
            } else {
                $this->session->$params['session_key'] = $params['value'];
            }
        }

        // set to view
        $this->view->paramsErrors = $paramsErrors;
        $this->view->params = $params;
    }

    public function sendMailAction()
    {
        // set params
        $params_array = array(
            'subject',
            'to',
            'from',
            'cc',
            'message',
            'submit',
        );

        // get param from input
        $params = $this->_getParamFromFields($params_array);
        $paramsErrors = array();

        if (!is_null($params['submit'])) {

            // set filters
            $filters = array(
                '*'         => 'StringTrim', // * to apply filter on all vars
            );

            // set validators
            $validators = array(
                'to'        => array('allowEmpty' => false, 'EmailAddress'),
                'from'      => array('allowEmpty' => false, 'EmailAddress'),
                'cc'        => array('allowEmpty' => true, 'EmailAddress'),
                'message'   => array('allowEmpty' => false),
                'subject'   => array('allowEmpty' => false),
            );

            // add filters and validator on $params
            $form = new Zend_Filter_Input($filters, $validators, $params);

            if ($form->hasInvalid()) {
                $paramsErrors = $form->getInvalid();
            } else {
                $mail = new BaseZF_Mail();

                //Subject
                $mail->setSubject($params['subject']);

                // HTML mail body
                $mail->setBodyHtml('<strong>' . $params['message'] . '</strong>');

                // Text mail body
                $mail->setBodyText($params['message']);

                // Add a attachment
                //$mail->addAttachment('page.pdf');

                // from
                $mail->setFrom($params['from'], 'from');

                // Add dest
                $mail->addTo($params['to'], 'to');

                // Add Hidden dest
                $mail->addBcc($params['cc'], 'cc');

                // And send mail !
                $mail->send();
            }
        }

        // set to view
        $this->view->paramsErrors = $paramsErrors;
        $this->view->params = $params;
    }

    public function redirectAction()
    {
        // redirect properly
        $this->_redirect('/Example');
    }

    public function forwardAction()
    {
        // forward($action, $controller = null, $module = null, $params = null)
        $this->_forward('index');
    }

    public function httpClientAction()
    {
        // set params
        $params_array = array(
            'url',
            'submit',
        );

        // get param from input
        $params = $this->_getParamFromFields($params_array);
        $paramsErrors = array();

        if (!empty($params['url'])) {

            try {

                $client = new Zend_Http_Client();
                $client->setUri($params['url']);

                // set config values
                $client->setConfig(array(
                    'maxredirects' => 0,
                    'timeout'      => 30
                ));

                $response = $client->request();
                $this->view->response_body = $response->getBody();
            } catch (Exception $e) {
                $this->view->error = $e->getMessage();
            }
        }

        $this->view->paramsErrors = $paramsErrors;
        $this->view->params = $params;
    }

    /**
     * Begin of form Example
     */
    public function formAction()
    {
        // set params
        $params_array = array(
            'text',
            'password',
            'select',
            'textarea',
            'checkbox',
            'radio',
            'submit',
            'no_ajax',
        );

        // get param from input
        $params = $this->_getParamFromFields($params_array);
        $paramsErrors = array();

        // if it ajax replace form by new
        if ($this->view->isAjax()) {
            $this->view->setJsCode('$(\'form_example\').replace(XHR.responseText)');
        }

        // set to view
        $this->view->paramsErrors = $paramsErrors;
        $this->view->params = $params;
    }

    public function formCheckAction()
    {
        // set params
        $params_array = array(
            'integer',
            'float',
            'mail',
            'alpha',
            'alpha-num',
            'alpha-num2',
            'date',
            'submit',
            'no_ajax',
        );

        // set default values
        $default_params_values = array(
            'integer'       => '10',
            'float'         => '100.1',
            'mail'          => 'test@example.org',
            'alpha'         => '@#123abc',
            'alpha-num'     => '@#123abc',
            'alpha-num2'    => '@#123abc',
            'date'          => '1985-04-14',
        );

        // get param from input
        $params = $this->_getParamFromFields($params_array);
        $paramsErrors = array();

        // set default values for $params
        foreach ($params as $key => $value) {
            if (is_null($value) && isset($default_params_values[$key])) {
                $params[$key] = $default_params_values[$key];
            }
        }

        // if form submited
        if (!is_null($params['submit'])) {

            // set filters
            $filters = array(
                '*'         => 'StringTrim',  // * to apply filter on all vars
            );

            // set validators
            $validators = array(
                'integer'       => array('Digits', 'messages' => '"%value%" must consist only of digits (personalized message)'),
                'float'         => 'Float',
                'mail'          => 'EmailAddress',
                'alpha'         => 'Alpha',
                'date'          => 'Date',
                'alpha-num'     => array('Alnum', 'allowEmpty' => false),
                'alpha-num2'    => array('Alnum', 'allowEmpty' => true),
            );

            // add filters and validator on $params
            $form = new Zend_Filter_Input($filters, $validators, $params);

            if ($form->hasInvalid()) {
                $paramsErrors = $form->getInvalid();
            } else {
                // do the insert or update here...
            }
        }

        // if it ajax replace form by new
        if ($this->view->isAjax()) {
            $this->view->setJsCode('$(\'form_example\').replace(XHR.responseText)');
        }

        // set to view
        $this->view->paramsErrors = $paramsErrors;
        $this->view->params = $params;
    }

    /**
     * Model object manipulation
     */
    public function addExampleModelAction()
    {
    }

    public function editExampleModelAction()
    {
    }

    public function searchExampleModelAction()
    {
        // set params
        $params_array = array(
            'page',
            'nb_per_page',
            'sort_field',
            'sort_order',
        );

        // get param from url
        $params = $this->_getParamFromFields($params_array);
        $property_filters = array();

        print_r($params);

        if (is_null($params['nb_per_page']) && $params['nb_per_page'] <= 50) {
            $params['nb_per_page'] = 10;
        }

		if (is_null($params['page'])) {
            $params['page'] = 1;
        }

        $this->view->search_example = BaseZF_Example::search(
            $params['page'],
            $params['nb_per_page'],
            $property_filters,
            $params['sort_field'],
            $params['sort_order']
        );

        // build pagination params
        $this->view->pagination_params = array();
        foreach ($params as $key => $value) {
            if (!is_null($value) && $key != 'page') {
                $this->view->pagination_params[$key] = $value;
            }
        }

        // set to view
        $this->view->current_page = $params['page'];
        $this->view->params = $params;
    }

    /**
     * Others Compoments
     */
    public function imageresizeAction()
    {
        $this->view->source_img = '/images/zf.jpg';
        $this->view->dest_img = '/images/zf_resized.jpg';

        // set params
        $params_array = array(
            'new_height',
            'new_width',
        );

        // set default values
        $default_params_values = array(
            'new_height'    => '100',
            'new_width'     => '100',
        );

        // get param from input
        $params = $this->_getParamFromFields($params_array);
        $paramsErrors = array();

        // set default values for $params
        foreach ($params as $key => $value) {
            if (is_null($value) && isset($default_params_values[$key])) {
                $params[$key] = $default_params_values[$key];
            }
        }

        // set filters
        $filters = array(
            '*'         => 'StringTrim',  // * to apply filter on all vars
        );

        // set validators
        $validators = array(
            'new_height'    => 'Digits',
            'new_width'     => 'Digits',
        );

        // add filters and validator on $params
        $form = new Zend_Filter_Input($filters, $validators, $params);

        if ($form->hasInvalid()) {
            $paramsErrors = $form->getInvalid();
        } else {
            $img = new BaseZF_Framework_Image(BASEZF_PATH_TO_DOCUMENT_ROOT . $this->view->source_img);
            $new_img = $img->basicConvert(BASEZF_PATH_TO_DOCUMENT_ROOT .  $this->view->dest_img, $params['new_width'], $params['new_height']);
        }

        // set to view
        $this->view->paramsErrors = $paramsErrors;
        $this->view->params = $params;
    }

    public function extGridAction()
    {
    	$this->view->addStyle('/js/ext/resources/css/xtheme-gray.css');
    	$this->view->addStyle('/js/ext/resources/css/ext-all.css');
    	$this->view->addJavascript('/js/ext/adapter/prototype/ext-prototype-adapter.js');
        $this->view->addJavascript('/js/ext/ext-all.js');
	}

	public function extGridCallBackAction()
    {

	}
}
